<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		*{
			padding:0;
			margin:0;
		}
		#a{
			width: 200px;
			height: 200px;
			background: skyblue;
			position: absolute;
			left: 200px;
			top:100px;
		}
		#b{
			width: 200px;
			height: 200px;
			background: orange;
			position: absolute;
			top:300px;
			left: 300px;
		}
	</style>
</head>
<body>
	<div id="a"></div>
	<div id="b"></div>
</body>
</html>
<script>
	//获取元素
	var aDiv = document.getElementById("a");
	aDiv.onmousedown = function(e){
		//记录初始位置
		var x = e.clientX - aDiv.offsetLeft;
		var y = e.clientY - aDiv.offsetTop;

		//事件委托，利用冒泡，将元素事件委托给父辈元素执行
		document.onmousemove = function(e){
			aDiv.style.left = e.clientX - x + "px";
			aDiv.style.top = e.clientY - y + "px";
			var p1 = {
				left:aDiv.offsetLeft,
				right:aDiv.offsetLeft + aDiv.offsetWidth,
				top:aDiv.offsetTop,
				bottom:aDiv.offsetTop + aDiv.offsetHeight
			};
			 var p2 = {
			 	left:b.offsetLeft,
			 	right:b.offsetLeft + b.offsetWidth,
			 	top:b.offsetTop,
				bottom:b.offsetTop + b.offsetHeight
			 };
			if(isCrash(p1,p2)){
				aDiv.style.background = "yellow";
				aDiv.style.zIndex = 1;
			}else{
				aDiv.style.background = "skyblue";
				aDiv.style.zIndex = 0;
			}
		};
		//鼠标抬起时结束移动事件
		this.onmouseup = function(){
			document.onmousemove = null;
		};
	};

	function isCrash(p1,p2){
		var r = p1.left > p2.right || p1.right < p2.left || p1.bottom < p2.top || p1.top > p2.bottom; 
		return !r;
	}
</script>